# -*- coding: UTF-8 -*-
import requests
from bs4 import BeautifulSoup
from PIL import Image
import re
import cookielib

agent = 'Mozilla/5.0 (Windows NT 5.1; rv:33.0) Gecko/20100101 Firefox/33.0'

headers = {
    "User-Agent": agent,
    "Host": "login.weibo.cn",
    "Origin": "https://login.weibo.cn",
    "Referer": "https://login.weibo.cn/login/"
}

session=requests.session()
session.cookies=cookielib.LWPCookieJar()

session.proxies={"127.0.0.1:8888"}

def login():
    r=session.get("http://login.weibo.cn/login/", headers=headers, allow_redirects=True)
    bsf=BeautifulSoup(r.text, "html.parser")
    img=bsf.find("img", {"alt":"请打开图片显示"});
    imgsrc=img['src']
    t=session.get(imgsrc, headers=headers, allow_redirects=True)
    with open("a.jpg", "wb") as f:
        f.write(t.content)
        f.close()
    try:
        image=Image.open("a.jpg")
        image.show()
        image.close()
    except:
        print "exception occur"
    pattern = r'action="(.*?)".*?type="password" name="(.*?)".*?name="vk" value="(.*?)".*?name="capId" value="(.*?)"'
    res = re.findall(pattern, r.text, re.S)
    return  res[0]
        

def doLogin():
    res=login()
    
    post_url, password, vk, capId = res
    
    capImg=raw_input("input:")
    postdata = {
        "mobile": "1002318371@163.com",
        password: "yanghui",
        "code": capImg,
        "remember": "on",
        "backURL": "http%3A%2F%2Fweibo.cn",
        "backTitle": "手机新浪网",
        "tryCount": "",
        "vk": vk,
        "capId": capId,
        "submit": "登录",
    }
    
    r=session.post(("http://login.weibo.cn/login/"+post_url).replace("&amp;", "&"), data=postdata, headers=headers, allow_redirects=False)
    print r.status_code
    index = session.get("http://weibo.cn")
    print(index.text)
    session.cookies.save("cookies")
doLogin()